package org.jeecg.modules.flowable.service;

import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FlowableService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private HistoryService historyService;

    /** 部署流程定义 */
    public String deployProcess() {
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("processes/leave-process.bpmn20.xml")
                .name("请假流程")
                .deploy();
        return deployment.getId();
    }

    /** 启动流程 */
    public ProcessInstance startLeaveProcess(String businessKey, String applicant, Integer days, String reason) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("applicant", applicant);
        variables.put("days", days);
        variables.put("reason", reason);
        return runtimeService.startProcessInstanceByKey("leaveProcess", businessKey, variables);
    }

    /** 查询待办任务 */
    public List<Task> getTasks(String assignee) {
        return taskService.createTaskQuery().taskAssignee(assignee).list();
    }

    /** 查询所有流程定义 */
    public List<ProcessDefinition> getProcessDefinitions() {
        return repositoryService.createProcessDefinitionQuery().list();
    }

    /** 完成任务 */
    public void completeTask(String taskId, Boolean approved, String approval) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("approved", approved);
        variables.put("approval", approval);
        taskService.complete(taskId, variables);
    }

    /** 查询流程实例 */
    public ProcessInstance getProcessInstance(String processInstanceId) {
        return runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
    }

    /** 查询历史任务 */
    public List<HistoricTaskInstance> getHistoryTasks(String processInstanceId) {
        return historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByTaskCreateTime()
                .asc()
                .list();
    }

    /** 获取流程变量 */
    public Map<String, Object> getProcessVariables(String processInstanceId) {
        return runtimeService.getVariables(processInstanceId);
    }
}